package com.lyloou.practice.factory;

import com.lyloou.practice.utils.TransactionManager;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.SQLException;

/**
 * @author lyloou
 * @date 2020/05/29
 * @desc
 */
public class ProxyFactory {
    TransactionManager transactionManager;

    public void setTransactionManager(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    public Object getJdkProxy(Object o) {
        return Proxy.newProxyInstance(o.getClass().getClassLoader(), o.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                return doMethod(o, method, args);
            }
        });
    }

    public Object getCglibProxy(Object target) {
        return Enhancer.create(target.getClass(), new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
                return doMethod(o, method, args);
            }
        });
    }

    private Object doMethod(Object o, Method method, Object[] args) throws SQLException, IllegalAccessException, InvocationTargetException {
        Object result;
        try {
            transactionManager.beginTransaction();
            result = method.invoke(o, args);
            transactionManager.commit();
        } catch (Exception e) {
            transactionManager.rollback();
            throw e;
        }

        return result;
    }

}
